package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    @Transactional
    public void deploy(MultipartFile bpmnFile, String bpmnType, String bpmnLabel, String info) throws IOException {
        //获取原始名称 leaveProcess.bpmn
        String originalFilename = bpmnFile.getOriginalFilename();
        //获取后缀bpmn
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if (!"bpmn".equalsIgnoreCase(extName)) {
            throw new BusinessException("流程文件只能是bpmn的格式");
        }
        //进行部署
        Deployment deployment = repositoryService.createDeployment()
                .addInputStream(originalFilename, bpmnFile.getInputStream())
                .deploy();

        //获取流程定义的key和version 需要查询流程定义的对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId())
                .singleResult();
        //封装bpmnInfo对象
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnLabel(bpmnLabel);
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setInfo(info);
        bpmnInfo.setProcessDefinitionKey(processDefinition.getKey());
        bpmnInfo.setVersion(processDefinition.getVersion());
        bpmnInfo.setDeployTime(new Date());
        bpmnInfoMapper.insert(bpmnInfo);

    }

    @Override
    public InputStream getFileInputStream(Long id, String type) {
        InputStream is = null;
        BpmnInfo bpmnInfo = this.get(id);
        String definitionKey = bpmnInfo.getProcessDefinitionKey();
        Integer version = bpmnInfo.getVersion();
        //获取到流程的定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(definitionKey)
                .processDefinitionVersion(version)
                .singleResult();
        String deploymentId = processDefinition.getDeploymentId();
        if ("xml".equalsIgnoreCase(type)) {
            //通过bpmninfo获取浏览器定义的key
            String xmlName = processDefinition.getResourceName();
            //需要有xml文件名称
            is = repositoryService.getResourceAsStream(deploymentId,xmlName);
        }else {
            //流程文件图模型对象
            BpmnModel model = repositoryService.getBpmnModel(processDefinition.getId());
            //流程文件图片生成器
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram（bpmn模型，需要高亮节点的id集合，需要高亮节点的id集合，字体，字体，字体）
            is = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        }
        return is;
    }

    @Override
    public void delete(Long id) {
        //根据id获取bpmn对象
        BpmnInfo bpmnInfo = this.get(id);
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        //查询当前流程定义有哪些流程实例
        List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(processDefinitionKey)
                .list();
        //找到所有的业务标识，通过业务标识更新对应的状态
        for (ProcessInstance instance : processInstanceList) {
            String businessKey = instance.getBusinessKey();
            //
        }
        String deploymentId = null;
        //判断获取取出的流程实例是否有对象
        if (processInstanceList.size() > 0) {
            //没有查询
            deploymentId = processInstanceList.get(0).getDeploymentId();
        }else {
            //获取流程定义对象
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionKey(processDefinitionKey)
                    .processDefinitionVersion(bpmnInfo.getVersion())
                    .singleResult();
            deploymentId = processDefinition.getDeploymentId();
        }
        //级联删除流程定义
        repositoryService.deleteDeployment(deploymentId,true);
        bpmnInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public BpmnInfo getByBpmnType(String bpmnType) {
        return bpmnInfoMapper.getByBpmnType(bpmnType);
    }
}

